/**
 * @author : wangbo
 * @date : 2020-11-01 17:46
 **/
package com.ohaku.aop;

import com.alibaba.druid.util.StringUtils;
import com.ohaku.anno.DefaultValue;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Aspect
@Component
public class DefaultValueAop {

    @Pointcut("execution(public * com.ohaku.controller..*.*(..))")
    public void setFieldParamPoint() {
    }

    @Before("setFieldParamPoint()")
    public void doBefore(JoinPoint joinPoint) {
    }

    @Around("setFieldParamPoint()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

        MethodSignature signature = ((MethodSignature) pjp.getSignature());
        Method method = signature.getMethod();
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        if (parameterAnnotations == null || parameterAnnotations.length == 0) {
            return pjp.proceed();
        }
        String[] paramNames = signature.getParameterNames();
        Object[] paranValues = pjp.getArgs();
        Class<?>[] parameterTypes = method.getParameterTypes();
        for (int i = 0; i < parameterAnnotations.length; i++) {
            for (int j = 0; j < parameterAnnotations[i].length; j++) {
                if (parameterAnnotations[i][j] != null && parameterAnnotations[i][j] instanceof DefaultValue &&
                        !StringUtils.isEmpty(((DefaultValue) parameterAnnotations[i][j]).value())) {
                    if (String.class.equals(parameterTypes[i])) {
                        paranValues[i] = ((DefaultValue) parameterAnnotations[i][j]).value();
                    }
                }


            }
        }
        return pjp.proceed(paranValues);
    }

    @AfterReturning(value = "setFieldParamPoint()", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, Object result) {

    }


}
